﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.ServiceModel.Channels;
using SMS_Gateway.com.smsglobal.www;
using System.Web;
using System.Net;
using System.Collections.Specialized;
 

namespace SMS_Gateway
{
    //TODO : Implement an Abstract class , to allow for changing the service provider ... which looks good so far :D
    public class SMSGobalGateway:SOAPGateway
    {
        enum GatewayStatus
        {
            Disconnected,
            NoCredit,
            Connected
        }
        public class resp
        {
            public string ticket { get; set; }
            public string sms { get; set; }
        }
        decimal _SMSBalance = 0;

        // TODO: IMplement an Event , to be called when the service gets disconnected , and so we can notify the interface

        string _ticket;
        string _senderID;
        MobileWorks _client;

        Credentials _cred;


        GatewayStatus _status;


        public void Login(Credentials cred) // TODO: Mabe Change this to Credentials struct and then use it here (abstraction)
        {
            try
            {
                _cred = cred;
                //CustomBinding bi = new CustomBinding();
                //bi.Elements.Add(new TextMessageEncodingBindingElement(_client.Endpoint.Binding.MessageVersion, Encoding.GetEncoding("iso-8859-1")));
                
                //_client.Endpoint.Binding = bi;
               
                string loginResponse= _client.apiValidateLogin(cred.Username, cred.Password);
                XmlSerializer loginSerializer = new XmlSerializer(typeof(resp));

                resp resp = (resp)loginSerializer.Deserialize(new StringReader(loginResponse));

                _ticket = resp.ticket;
                _status = GatewayStatus.Connected;
            }
            catch
            {
                _status = GatewayStatus.Disconnected;
            }
        }

        public override bool IsConnected
        {
            get
            {

                //TODO: Implement the procedure
                return (_status == GatewayStatus.Connected) && !String.IsNullOrEmpty(_ticket);
            }
        }

        public string SenderID
        {
            get
            {
                return _senderID;
            }
            set
            {
                if (!String.IsNullOrEmpty(_senderID))
                {
                    _senderID = value;
                }
            }
        }

        public decimal SMSBalance
        {
            get
            {
                //TODO: IMPLEMENT
                try
                {
                    if (this._status != GatewayStatus.NoCredit && _SMSBalance==0) // never requested the balance
                    {
                        string balanceResponse = _client.apiBalanceCheck(_ticket, "EG");

                        XmlSerializer loginSerializer = new XmlSerializer(typeof(resp));
                        resp resp = (resp)loginSerializer.Deserialize(new StringReader(balanceResponse));
                        _SMSBalance = decimal.Parse(resp.sms);

                        if (_SMSBalance == 0)
                        {
                            this._status = GatewayStatus.NoCredit;
                        }
                    }
                    return _SMSBalance;
                }
                catch (Exception)
                {

                    throw;
                }
            }

        }



        public override bool SendSingleSMSTo(Credentials cred, SingleSMS sms, SMSContact cont, bool unicode)
        {
            if (IsConnected && SMSBalance > 0)
            {


                string sendSMSResponse;
                string message = (unicode) ? System.Uri.EscapeDataString(sms.SMS_Body) : sms.SMS_Body;
                //string message = sms.SMS_Body; 

                if (SingleSMS.IsValid(sms) && SMSContact.IsValid(cont))
                {
                    sendSMSResponse = _client.apiSendSms(_ticket, _senderID, "2" + cont.Number, message, "text", "0", "");
                }



                // TODO : implemnt success or failture
                _SMSBalance--;
                return true;
            }
            else
            {
                throw new Exception("Disconnected");
            }

        }

        public SMSGobalGateway(string senderID)
        {
            _senderID = senderID;
            _client = new MobileWorks();
            _status = GatewayStatus.Disconnected;
        }

        public override void  LogOut()
        {
            string logoutResponse= _client.apiLogout(_ticket);

            // Implement response
        }
    }
}
